<?php

namespace Common\Service;
use Common\Service\Wechat;
use Think\Log;


//模板消息
class Tpl{

	private $_access_token;
  	private $_url;

	public function __construct(){


		$wemodel = new Wechat();
        $this->_access_token = $wemodel->getAccessToken();
        $this->_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$this->_access_token";
  }


	/*
    您好，您已成功消费。
    {{productType.DATA}}：{{name.DATA}}
    消费时间：{{time.DATA}}
    {{remark.DATA}}
     */
    public function sendtpl($openId,$type,$time,$remark,$deviceid){

        $url = $this->_url;
        $template_id = 'tHqhUIz1KK0WMcBc1RkGZ9HC_b2hxIII-NjQvtBt0V8';

        $url = "http://znth.xiutub.com/device/record?id=".$deviceid;

        $data = ' {
           "touser":"'.$openId.'",
           "template_id":"'.$template_id.'",
           "url":'.$url.',
           "data":{

               "first":{
                   "value":"您好，卫嘉智能药盒提醒您",
                   "color":"#173177"
               },
               "keyword1": {
                   "value":"'.$type.'",
                   "color":"#173177"
               },
               "keyword2": {
                   "value":"'.$time.'",
                   "color":"#173177"
               },
               "remark":{
                   "value":"\n'.$remark.'",
                   "color":"#173177"
               }
           }

        }';


        $ret = $this->http_post($url,$data,true);
        $ret = json_decode($ret);
        return $ret->errmsg;
    }

    //http post请求
    public function http_post($url, $data, $ssl = FALSE){

        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if($ssl){
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        }

        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);

        if($res === false){
            Log::write('Tpl Curl error：'.curl_error($curl));
            return FALSE;
        }
        curl_close($curl);
        return $res;
    }
}